#!/usr/bin/env python3
"""Get execution summary of the tests."""
import argparse
import sys

from cki_lib import misc
from cki_lib.kcidb.file import KCIDBFile
import sentry_sdk


def get_single_test_summary(test_data):
    """Get the test summary of a single test.

    Returns the test status if the test is not waived, PASS otherwise.
    Test without status (testplan) return MISS.
    """
    if test_data.get('waived', False):
        return 'PASS'
    return test_data.get('status', 'MISS')


def get_execution_summary(kcidb_file):
    """Compute the summary of all executed tests and map it to retcodes."""
    tests = kcidb_file.data.get('tests')
    if not tests:
        return 'PASS'

    test_summaries = [get_single_test_summary(test) for test in tests]

    if any(summary == 'FAIL' for summary in test_summaries):
        return 'FAIL'
    if any(summary == 'ERROR' for summary in test_summaries):
        return 'ERROR'
    if any(summary == 'MISS' for summary in test_summaries):
        return 'MISS'

    # SKIP, PASS, DONE are all treated as PASS for the purposes of marking the
    # pipeline as passing or failing.
    return 'PASS'


def parse_args(argv):
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description='Get test execution summary from a KCIDB file.'
    )

    parser.add_argument(
        'kcidb_file',
        type=str,
        help='A path to the KCIDB file to read.',
    )

    return parser.parse_args(argv)


def main(argv):
    """Open the file and get the summary."""
    args = parse_args(argv)
    kcidb_file = KCIDBFile(args.kcidb_file)
    print(get_execution_summary(kcidb_file))


if __name__ == '__main__':
    misc.sentry_init(sentry_sdk)
    main(sys.argv[1:])
